<?php

namespace EasyTiktokSdk\Auth;


class OAuth extends AccessToken
{

    protected function getAuthBaseUri()
    {
        if ($this->app['config']['is_us']) {
            $authBaseUri = 'https://services.us.tiktokshop.com/open/authorize';
        } else {
            $authBaseUri = 'https://services.tiktokshop.com/open/authorize';
        }

        return $authBaseUri;
    }

    /**
     * Return the pre-authorization login page url (mobile).
     *
     *
     * @return string
     */
    public function redirect()
    {
        $queries = [
            'app_key' => $this['config']['app_key'],
            'state' => 'get_token'
        ];

        return $this->getAuthBaseUri() . '?' . http_build_query($queries);
    }

    public function getTokenFromCode($code)
    {
        $params = [
            'app_key' => $this->app['config']['app_key'],
            'app_secret' => $this->app['config']['app_secret'],
            'auth_code' => $code,
            'grant_type' => 'authorized_code'
        ];

        $response = $this->request('/api/v2/token/get', $params);

        $result = json_decode($response->getBody()->getContents(), true);

        if (0 != $result['code'] && empty($result['data']['access_token'])) {
            throw new \Exception('Request access_token fail: '.json_encode($result, JSON_UNESCAPED_UNICODE), $response);
        }

        $this->setToken($result['data']);

        return $result['data'];
    }

}